configparser 模块主要用于生成配置文件和对配置文里的内容进行修改

configparser 模块现在很少使用到,现在直接用 .py 的文件作为配置文件

1. 生成配置文件

import configparser

# 配置文件的内容
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11': 'yes'
                     }
config['bitbucket.org'] = {'User': 'hg'}

config['topsecret.server.com'] = {'Host Port': '50022', 'ForwardX11': 'no'}

# 将配置文件内容写入文件
with open('example.ini', 'w') as f:
    config.write(f)

# 配置文件 example.ini

[DEFAULT]
serveraliveinterval = 45
compressionlevel = 9
forwardx11 = yes
compression = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
forwardx11 = no
host port = 50022

2. 查找文件的相关操作

import configparser

config = configparser.ConfigParser()
config.read('example.ini')  # 获取配置文件的操作符

print(config.sections())  # 获取除 DEFAULT 外的配置文件里的组名,因为 DEFAULT 是特殊的

print('bitbucket.org' in config)  # 判断该组名是否在该配置文件里

print(config['bitbucket.org']["user"])  # hg 获取配置文件里的值

print(config['bitbucket.org'])  # <Section: bitbucket.org>

for key in config['bitbucket.org']:  # 如果配置文件中有 DEFAULT 那么它下面的 key 也会被打印出来
    print(key)

print(config.options('bitbucket.org'))  # 获取'bitbucket.org'下所有键,以列表的形式返回

print(config.items('bitbucket.org'))  # 获取'bitbucket.org'下所有键值对,以列表的形式返回

print(config.get('bitbucket.org', 'compression'))  # yes 用get方法获取Section下的key对应的value

3. 增 删 改 操作

import configparser
import os

config = configparser.ConfigParser()
config.read('example.ini')  # 读文件
config.add_section('yuan')  # 增加section
config.remove_section('bitbucket.org')  # 删除一个section
config.remove_option('topsecret.server.com', "forwardx11")  # 删除一个配置项
config.set('topsecret.server.com', 'k1', '11111')  # 设置一个配置项
config.set('yuan', 'k2', '22222')  # 设置一个配置项

f = open('example.bak', "w")
config.write(f)  # 写进文件
f.close()
os.remove('example.ini')
os.rename('example.bak', 'example.ini')